import { Config } from "./config.js";
let app = new getApp();
class Utils {
    constructor() {
            this.base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            this.base64DecodeChars = new Array(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
                52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
                15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
                41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);
        }
        /*限制字数
        worlds:原内容；
        worldlength:显示的长度
        mark:超出部分显示的字符
        */
    limitworld(worlds, wordlength, mark) {
        var nowLength = worlds.length;
        var newWorlds = "";
        if (nowLength > wordlength) {
            newWorlds = worlds.substr(0, wordlength) + mark;
        } else {
            newWorlds = worlds;
        }
        return newWorlds;
    }
    truncated(str, num) {
            let nickname = Array.from(str);
            let s = '';
            for (let v of nickname) {
                s += v;
                num--;
                if (num <= 0) {
                    break;
                }
            }
            return s;
        }
        // 获取元素绑定的值
    getDataSet(event, key) {
        return event.currentTarget.dataset[key];
    }

    // 判断是否是手机号码
    isMobile(mobile) {
        return !!mobile.match(/^(0|86|17951)?(13[0-9]|15[012356789]|17[3678]|18[0-9]|14[57])[0-9]{8}$/);
    }

    // 转换时间参数yyyy-mm-dd hh:mm:ss
    timestampFormat(time) {
        let mytime = time.replace(/-/g, "/");

        function zeroize(num) {
            return (String(num).length == 1 ? '0' : '') + num;
        }
        let timestamp = parseInt(new Date(mytime).getTime() / 1000);
        let curTimestamp = parseInt(new Date().getTime() / 1000);
        let timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数

        let curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
        let tmDate = new Date(timestamp * 1000); // 参数时间戳转换成的日期对象
        let Y = tmDate.getFullYear(),
            m = tmDate.getMonth() + 1,
            d = tmDate.getDate();
        let H = tmDate.getHours(),
            i = tmDate.getMinutes(),
            s = tmDate.getSeconds();
        if (timestampDiff < 60) { // 一分钟以内
            return "刚刚";
        } else if (timestampDiff < 3600) { // 一小时前之内
            return Math.floor(timestampDiff / 60) + "分钟前";
        } else if (curDate.getFullYear() == Y && curDate.getMonth() + 1 == m && curDate.getDate() == d) {
            return "今日 "+zeroize(H) + ':' + zeroize(i);
        } else {
            let newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
            if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
                return '昨天' + zeroize(H) + ':' + zeroize(i);
            } else if (curDate.getFullYear() == Y) {
                return zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
            } else {
                return Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
            }
        }
    }

    // 预览图片
    /*
    index:Number---显示图片的索引值
    urls:Array---图片数组
    */
    previewImage(index, urls) {
        let allurls = urls.map((url) => {
            return url + "?x-oss-process=image/format,jpg/watermark,image_SW1hZ2Vfd2F0ZXIvaW1hZ2Vfd2F0ZXIucG5nP3gtb3NzLXByb2Nlc3M9aW1hZ2UvcmVzaXplLFBfMTA,t_100,g_se,y_15,x_15"
        });
        wx.previewImage({
            current: allurls[index],
            urls: allurls
        })
    }
    safeGet(keyList, obj) { return keyList.reduce((preValue, curKey) => ((preValue && preValue[curKey]) ? preValue[curKey] : null), obj) }
    getLocationUrl(latitude, longitude) { return `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${Config.key}` }
        //获取经纬度
    _getLatLng(lat, lng, callBack) {
            let that = this;
            wx.getLocation({
                type: 'gcj02',
                success(res) {
                    const latitude = res.latitude
                    const longitude = res.longitude
                    wx.setStorageSync("lat", latitude);
                    wx.setStorageSync("lng", longitude);
                    wx.request({
                        url: that.getLocationUrl(latitude, longitude),
                        success: res => {
                            const { adcode, city } = that.safeGet(['data', 'result', 'ad_info'], res);
                            let {
                                provinceID,
                                cityID,
                                regionID
                            } = that.getAreaCode(adcode);
                            wx.setStorageSync("provinceID", provinceID);
                            wx.setStorageSync("cityID", cityID);
                            wx.setStorageSync("regionID", regionID);
                            wx.setStorageSync('city', city);
                        }
                    })
                    callBack && callBack(that._getKm(lat, lng));
                }
            })
        }
        // 错误统一处理
    _error() {
            wx.showToast({
                title: '网络错误，稍后再试',
                icon: "none"
            })
            setTimeout(() => {
                wx.navigateBack({})
            }, 500);
        }
        //视频长度转时间
    lengthToTime(time) {
            let newTime = "";
            if (time <= 9) {
                newTime = "00:0" + time;
            } else if (time > 9 && time <= 60) {
                newTime = "00:" + time;
            } else {
                let minute = parseInt(time / 60);
                let second = time % 60;
                if (second <= 9) {
                    second = "0" + second;
                }
                if (minute <= 9) {
                    minute = "0" + minute;
                }
                newTime = minute + ":" + second;
            }
            return newTime;
        }
        //获取省市区
    getAreaCode(code) {
            if (!code) {
                return false;
            }
            let provinceCode = code.substring(0, 3) + "000";
            let cityCode = code.substring(0, 4) + "00";
            return {
                provinceID: provinceCode,
                cityID: cityCode,
                regionID: code
            }
        }
        //在数组中查找值
    findStrFromArray(arr, str) {
            if (arr.constructor !== Array) {
                return false;
            }
            const right = arr.filter((val) => {
                return val == str;
            });
            if (right.length > 0) {
                return true
            } else {
                return false
            }
        }
        //编码的方法
    base64encode(str) {
            var out, i, len;
            var c1, c2, c3;
            len = str.length;
            i = 0;
            out = "";
            while (i < len) {
                c1 = str.charCodeAt(i++) & 0xff;
                if (i == len) {
                    out += this.base64EncodeChars.charAt(c1 >> 2);
                    out += this.base64EncodeChars.charAt((c1 & 0x3) << 4);
                    out += "==";
                    break;
                }
                c2 = str.charCodeAt(i++);
                if (i == len) {
                    out += this.base64EncodeChars.charAt(c1 >> 2);
                    out += this.base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                    out += this.base64EncodeChars.charAt((c2 & 0xF) << 2);
                    out += "=";
                    break;
                }
                c3 = str.charCodeAt(i++);
                out += this.base64EncodeChars.charAt(c1 >> 2);
                out += this.base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                out += this.base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
                out += this.base64EncodeChars.charAt(c3 & 0x3F);
            }
            return out;
        }
        //解码的方法
    base64decode(str) {
            var c1, c2, c3, c4;
            var i, len, out;
            len = str.length;
            i = 0;
            out = "";
            while (i < len) {

                do {
                    c1 = this.base64DecodeChars[str.charCodeAt(i++) & 0xff];
                } while (i < len && c1 == -1);
                if (c1 == -1)
                    break;

                do {
                    c2 = this.base64DecodeChars[str.charCodeAt(i++) & 0xff];
                } while (i < len && c2 == -1);
                if (c2 == -1)
                    break;
                out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

                do {
                    c3 = str.charCodeAt(i++) & 0xff;
                    if (c3 == 61)
                        return out;
                    c3 = this.base64DecodeChars[c3];
                } while (i < len && c3 == -1);
                if (c3 == -1)
                    break;
                out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

                do {
                    c4 = str.charCodeAt(i++) & 0xff;
                    if (c4 == 61)
                        return out;
                    c4 = this.base64DecodeChars[c4];
                } while (i < len && c4 == -1);
                if (c4 == -1)
                    break;
                out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
            }
            return out;
        }
        //绘制图片
    drawImg(id, url, num, callback) {
            console.log(num);
            let ctx = wx.createCanvasContext(id, this);
            ctx.drawImage(url, 0, 0, 44, 44);
            ctx.setFontSize(16);
            ctx.setTextAlign("center");
            ctx.setTextBaseline("middle");
            ctx.fillText(num, 15, 15);
            ctx.draw(false, () => {
                console.log(num);
                wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    width: 44,
                    height: 44,
                    destWidth: 44,
                    destHeight: 44,
                    canvasId: id,
                    success(res) {
                        callback(res.tempFilePath);
                    },
                    fail: err => {
                        console.log(err);
                    }
                })
            });
        }
        //随机整数
    getRandomIntInclusive(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
}

export { Utils }